package com.telit.android.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.telit.android.dto.AppSignInDto;
import com.telit.android.entity.AppSignIn;
import com.telit.android.service.AppSignInService;
import com.telit.common.entity.DataReturn;
import com.telit.common.entity.PageData;
import com.telit.common.enums.ResultCode;
import com.telit.common.util.MediaUrlUtils;
import com.telit.firecommand.feign.RemoteFirecommandService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;


/**
 * @Author:zhangwei
 * @Description:
 * @Time:Created on 2021/9/1 14:10
 */
@RestController
@RequestMapping("/app-sign-in")
@Api(tags = "用户签到信息表",description = "/app-sign-in")
public class AppSignInController {
    
    @Autowired
    AppSignInService appSignInService;

    @Autowired
    private RemoteFirecommandService fireCommandFeignClient;

    @PostMapping(value="/add",produces = "application/json;charset=UTF-8")
    @ApiOperation("新增用户签到信息")
    public DataReturn add(@RequestBody AppSignIn appSignIn, @RequestParam(value = "files", required = false) List<MultipartFile> files){
//        if(!CollectionUtils.isEmpty(files)){
//            List<String> imgList = new ArrayList<>();
//            for (MultipartFile file : files) {
//                // 调用minio-server接口传入图片
//                imgList.add(MinioUtils.upload(file, MinioConstants.BUCKET_FORESTRY_NAME,MinioConstants.BUCKET_ANDRIOD_SUFFIX_NAME));
//            }
//            appSignIn.setImageUrl(JSONObject.toJSONString(imgList));
//        }
       /* //根据经纬度反查行政区划编码和名称
        if(ObjectUtil.isNotEmpty(appSignIn.getLongitude()) && ObjectUtil.isNotEmpty(appSignIn.getLatitude())){
            DataReturn districtNameAndCodeByPoint = fireCommandFeignClient.getDistrictNameAndCodeByPoint(Convert.toStr(appSignIn.getLongitude()), Convert.toStr(appSignIn.getLatitude()));
            if(ObjectUtil.isNotEmpty(districtNameAndCodeByPoint.getData())){
                Map<String, String> codeAndNameMap = Convert.toMap(String.class, String.class, districtNameAndCodeByPoint.getData());
                //添加签到的行政区划编码和名称
                appSignIn.setDistrictCode(codeAndNameMap.get("districtcode"));
                appSignIn.setDistrictName(codeAndNameMap.get("districtname"));
            }else {
                //设置行政区划名称为“不在浦口区范围内”
                appSignIn.setDistrictName("不在浦口区范围内");
            }
        }*/
        appSignIn.setSignInTime(new Date());
        appSignIn.setCreateTime(new Date());
        appSignIn.setUpdateTime(new Date());
        appSignInService.add(appSignIn);
        return DataReturn.ok();
    }

    @PostMapping(value="/listByPage/{current}/{size}",produces = "application/json;charset=UTF-8")
    @ApiOperation("分页条件查询用户签到信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "页码", paramType = "path", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", paramType = "path", dataType = "int")
    })
    public DataReturn listByPage(@PathVariable("current") Integer current,
                                 @PathVariable("size") Integer size,
                                 @RequestBody(required = false) AppSignIn appSignIn){
        IPage<AppSignIn> appSignInIPage=appSignInService.selectByPage(current,size,appSignIn);

        //转换文件预览地址
        List<AppSignIn> appSignInList=appSignInIPage.getRecords();
        List<AppSignIn> resultList=new ArrayList<AppSignIn>();
        if(appSignInList!=null && appSignInList.size()>0){
            appSignInList.forEach(object->{
                if(StringUtils.isNotEmpty(object.getImageUrl())){
                    object.setPreviewUrl(MediaUrlUtils.handleMediaUrlToList(object.getImageUrl()));
                }
                resultList.add(object);
            });
        }

        return DataReturn.ok(new PageData<>((int)appSignInIPage.getTotal(),current,size,resultList));
    }

    @PostMapping(value="/searchListByPage/{current}/{size}",produces = "application/json;charset=UTF-8")
    @ApiOperation("根据条件分页条件查询用户签到信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "页码", paramType = "path", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", paramType = "path", dataType = "int")
    })
    public DataReturn searchListByPage(@PathVariable("current") Integer current,
                                 @PathVariable("size") Integer size,
                                 @RequestBody(required = false) AppSignInDto appSignInDto){
        try {
            IPage<AppSignIn> appSignInIPage = appSignInService.searchListByPage(current, size, appSignInDto);

            //转换文件预览地址
            if (appSignInIPage != null && appSignInIPage.getRecords() != null) {
                List<AppSignIn> appSignInList = appSignInIPage.getRecords();
                List<AppSignIn> resultList = new ArrayList<AppSignIn>();
                if (appSignInList != null && appSignInList.size() > 0) {
                    appSignInList.forEach(object -> {
                        if (StringUtils.isNotEmpty(object.getImageUrl())) {
                            object.setPreviewUrl(MediaUrlUtils.handleMediaUrlToList(object.getImageUrl()));
                        }
                        resultList.add(object);
                    });
                }

                return DataReturn.ok(new PageData<>((int) appSignInIPage.getTotal(), current, size, resultList));
            }
            return DataReturn.ok(new PageData<>(0, current, size, null));
        }catch (Exception e){
            return DataReturn.failure(ResultCode.SERVER_ERROR,e.getCause().getMessage());
        }
    }

    @PostMapping(value="/list",produces = "application/json;charset=UTF-8")
    @ApiOperation("无分页条件查询用户签到信息")
    public DataReturn list(@RequestBody(required = false) AppSignIn appSignIn){
        List<AppSignIn> appSignInList=appSignInService.selectByNoPage(appSignIn);
        List<AppSignIn> resultList=new ArrayList<AppSignIn>();
        if(appSignInList!=null && appSignInList.size()>0){
            appSignInList.forEach(object->{
                if(StringUtils.isNotEmpty(object.getImageUrl())){
                    object.setPreviewUrl(MediaUrlUtils.handleMediaUrlToList(object.getImageUrl()));
                }
                resultList.add(object);
            });
        }
        return DataReturn.ok(resultList);
    }

    @PostMapping(value="/update",produces = "application/json;charset=UTF-8")
    @ApiOperation("修改用户签到信息")
    public DataReturn update(@RequestBody AppSignIn appSignIn){
        appSignIn.setUpdateTime(new Date());

        //根据经纬度反查行政区划编码和名称
        if(ObjectUtil.isNotEmpty(appSignIn.getLongitude()) && ObjectUtil.isNotEmpty(appSignIn.getLatitude())){
            //根据ID查询签到信息
            AppSignIn retAppSignIn=appSignInService.selectById(appSignIn.getId());
            if(ObjectUtil.isEmpty(retAppSignIn) ){
                return DataReturn.ok("该签到信息不存在");
            }
            if(ObjectUtil.notEqual(appSignIn.getLongitude(),retAppSignIn.getLongitude()) || ObjectUtil.notEqual(appSignIn.getLatitude(),retAppSignIn.getLatitude())){
                DataReturn districtNameAndCodeByPoint = fireCommandFeignClient.getDistrictNameAndCodeByPoint(Convert.toStr(appSignIn.getLongitude()), Convert.toStr(appSignIn.getLatitude()));
                if(ObjectUtil.isNotEmpty(districtNameAndCodeByPoint.getData())){
                    Map<String, String> codeAndNameMap = Convert.toMap(String.class, String.class, districtNameAndCodeByPoint.getData());
                    //添加签到的行政区划编码和名称
                    appSignIn.setDistrictCode(codeAndNameMap.get("districtCode"));
                    appSignIn.setDistrictName(codeAndNameMap.get("districtName"));
                }else {
                    //设置行政区划名称为“不在浦口区范围内”
                    appSignIn.setDistrictName("不在查询范围内");
                }
            }

        }
        appSignInService.updateData(appSignIn);
        return DataReturn.ok();
    }

    @GetMapping("/delete/{id}")
    @ApiOperation(value = "根据ID删除用户签到信息")
    public DataReturn delete(@PathVariable("id") Long id){
        appSignInService.deleteById(id);
        return DataReturn.ok();
    }

    @GetMapping("/getSignDayNumMonth")
    @ApiOperation(value = "根据用户ID查询当月签到天数")
    public DataReturn getSignDayNumMonth(@RequestParam("userId") Long userId){
        int dayNum=appSignInService.getSignDayNumMonth(userId);
        Map<String,Integer> dataMap=new HashMap<>();
        dataMap.put("dayNum",dayNum);
        return DataReturn.ok(dataMap);
    }

    @GetMapping("/listSignDayByMonth")
    @ApiOperation(value = "根据用户ID和日期（年-月）查询月签到日信息列表,signDate为空默认查当月")
    public DataReturn listSignDayByMonth(@RequestParam("userId") Long userId,@RequestParam("signDate")String signDate ){
        List<Map<String,Object>> list=appSignInService.listSignDayByMonth(userId,signDate);
        return DataReturn.ok(list);
    }

    @GetMapping("/listSignDayNumByYear")
    @ApiOperation(value = "根据用户ID查询当年每个月签到天数")
    public DataReturn listSignDayNumByYear(@RequestParam("userId") Long userId,@RequestParam("year") String year){
        List<Map<String,Object>> list=appSignInService.listSignDayNumByYear(userId,year);
        return DataReturn.ok(list);
    }

    @GetMapping("/getSignInfoByDate")
    @ApiOperation(value = "根据用户ID和日期（年-月-日）查询日签到信息")
    public DataReturn getSignInfoByDate(@RequestParam("userId") Long userId,@RequestParam("signDate")String signDate ){
        AppSignIn info=appSignInService.getSignInfoByDate(userId,signDate);
        if (ObjectUtil.isNotEmpty(info)) {
            if(StringUtils.isNotEmpty(info.getImageUrl())){
                info.setPreviewUrl(MediaUrlUtils.handleMediaUrlToList(info.getImageUrl()));
            }
        }

        return DataReturn.ok(info);
    }
        
}
